package com.wsfk.ssm.tools;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.imageio.ImageIO;

import com.swetake.util.Qrcode;
import com.wsfk.ssm.messages.CodeMessage;

public class QRCodeUtil {

	//创建二维码
	public static void createQRcode(String path,CodeMessage codeMessage){
		Qrcode qrcode=new Qrcode();  
        qrcode.setQrcodeErrorCorrect('M');  
        qrcode.setQrcodeEncodeMode('B');  //设置二维码的编码模式
        qrcode.setQrcodeVersion(7); 
        
        byte[] d=null;
		try {
			String content =JsonUtil.jsonStringForObject(codeMessage);
			d = content.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} 
		
		BufferedImage bi = new BufferedImage(139, 139, BufferedImage.TYPE_INT_RGB);  
        // createGraphics  
        Graphics2D g = bi.createGraphics();  
        // set background  
        g.setBackground(Color.WHITE);  
        g.clearRect(0, 0, 139, 139);  
          
        g.setColor(Color.BLACK);  
          
        if (d.length>0 && d.length <123){  
            boolean[][] b = qrcode.calQrcode(d);     
            for (int i=0;i<b.length;i++){  
                  
                for (int j=0;j<b.length;j++){  
                    if (b[j][i]) {  
                        g.fillRect(j*3+2,i*3+2,3,3);  
                    }  
                }  
              
            }  
        }  
          
        g.dispose();  
        bi.flush();    
        File f = new File(path); 
        if(!f.exists()){
        	f.mkdirs();
        }
          
        try {
			ImageIO.write(bi, "png", f);
		} catch (IOException e) {
			e.printStackTrace();
		}   
	}
	
}
